package com.ymt.bpm.util;

import java.util.Calendar;

import org.apache.commons.lang.StringUtils;

public class BizNoUtil {

	/**
	 * 生成单号
	 * @param bizNoPattern
	 * @return
	 */
	public static String generateBizNo(String bizNoPattern, int seqNo) {
		Calendar cal = Calendar.getInstance();
		bizNoPattern = bizNoPattern.toUpperCase();
		
		//find SEQx pattern
		int noLen = 6;
		String[] vars = RegExUtil.findEmbracedVars(bizNoPattern);
		String seqVar = "SEQ";
		if (vars==null || vars.length==0) {
			return bizNoPattern;
		} else {
			for (int i=0; i<vars.length; i++) {
				if (vars[i].startsWith("SEQ")) {
					seqVar = "{"+vars[i]+"}";
					if (vars[i].length()>3) {
						String s = vars[i].substring(3);
						if (StringUtils.isNumeric(s)) {
							int si = Integer.parseInt(s);
							noLen = (si>8 || si<0) ? 8 : si;
						}
					}
				}
			}
		}
		String seqNoStr = String.valueOf(seqNo);
		while (seqNoStr.length()<noLen) {
			seqNoStr = "0"+seqNoStr;
		}
		
		bizNoPattern = StringUtils.replace(bizNoPattern, seqVar, seqNoStr);
		bizNoPattern = StringUtils.replace(bizNoPattern, "{YYYY}", String.valueOf(cal.get(Calendar.YEAR)));
		String mm = String.valueOf(cal.get(Calendar.MONTH)+1);
		if (mm.length()==1) {
			mm = "0" + mm;
		}
		bizNoPattern = StringUtils.replace(bizNoPattern, "{MM}", mm);
		String dd = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
		if (dd.length()==1) {
			dd = "0" + dd;
		}
		bizNoPattern = StringUtils.replace(bizNoPattern, "{DD}", dd);
		return bizNoPattern;
	}
	
	
	/*public static void main(String[] args) {
		System.out.println(generateBizNo("SBXJ{YYYY}{MM}{DD}-{SEQ6}", 5));
	}*/
}
